package com.lovo.common.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lovo.common.bean.UserInfoBean;
import com.lovo.common.dao.IUserInfoDAO;
import com.lovo.common.result.GlobalHandleException;
import com.lovo.common.result.Result;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class WebUtil {
    public static String SERVER_NAME = "";
    public static void writeValueAsString(ServletResponse response, Result result) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(mapper.writeValueAsString(result));
    }
    public static UserInfoBean verifyToken(String token, IUserInfoDAO userInfoDAO) throws IOException {
        if(token == null){
            return null;
        }
        String userName = null;
        try {
            userName = JWTUtil.getAudience(token);
        } catch (GlobalHandleException e) {
            return null;
        }
//        UserInfoBean userInfoBean = userInfoService.selectByUserName(userName);
        UserInfoBean userInfoBean = userInfoDAO.selectOne(new QueryWrapper<UserInfoBean>().eq("user_name",userName));
        if(userInfoBean == null){
            return null;
        }
        try {
            JWTUtil.verifyToken(token,userInfoBean.getUserPass());
        } catch (GlobalHandleException e) {
            return null;
        }

        return userInfoBean;
    }

    /**
     * 获取请求信息中的token
     * @param request
     * @return
     */
    public static String getToken(ServletRequest request){
        HttpServletRequest httpServletRequest = ((HttpServletRequest)request);
        String token = httpServletRequest.getHeader("token");
        if(token == null || "".equals(token)){
            Cookie[] cookies = httpServletRequest.getCookies();
            if(cookies != null){
                for(Cookie cookie : cookies){
                    if(cookie.getName().equals("token")){
                        token = cookie.getValue();
                    }
                }
            }
        }
        return token;
    }
}
